package com.istock.union.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class RandImage {

	private static String[] _CodeChar = { "2", "3", "4", "5", "6", "8", "9",
			"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "r", "s",
			"u", "x", "y", "z" };

	// Font Name, 支持多个用,分割, 如Tahoma,Arial
	private static String[] _CodeFontName = { "Arial", "TahomaAgency FB",
			"Tahoma", "Book Antiqua" }; // 支持的字体，可根据安装了的字体进行配置，但每添加一种字体进来的时候需要单独测试一下字体的效果
	// Font Size
	// Background Color
	private static Color _CodeBackgroundColor = new Color(238, 238, 238); // 背景色

	private static int _CodeFontSizeRandScope = 6; // 字体大小随机变化的范围
	private static int _CodeMaxTurnAngle =25; // 随机旋转最大角度

	private StringBuilder sRand = null;// 验证码图片中的文字
	private int count = 0;
	private String[] sRand_Image = null;

	public RandImage(int count) throws Exception {
		sRand = new StringBuilder("");
		this.count = count;
		if (count < 1) {
			throw new Exception("验证码图片中文字个数不能为空！");
		}
		Random random = new Random();
		sRand_Image = new String[count];
		String rn = null;
		for (int i = 0; i < count; i++) {
			rn = _CodeChar[random.nextInt(_CodeChar.length)];
			sRand.append(rn);
			sRand_Image[i] = rn;
		}
	}

	/**
	 * 直接得到随机的文字， 本方法和creatImage（）方法没有任何关系
	 * 
	 * @param count
	 *            随机文字的个数
	 * @return
	 */
	public String getRandomString() {
		if (sRand == null) {
			return "";
		}
		return sRand.toString();
	}

	/**
	 * 得到随机文字组成的图片。 本方法和getRandomString（）方法没有任何关系
	 * 
	 * @param count
	 *            随机文字的个数
	 * @return
	 */
	public BufferedImage creatImage() {
		Random random = new Random();
		System.setProperty("java.awt.headless", "true");
		// 在内存中创建图象
		// int width = 60, height = 20;
		int width = 8 * count * 3 + 8;
		int height = 14 * 3 + 2;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		// 获取图形上下文
		Graphics2D g = image.createGraphics();
		g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
				RenderingHints.VALUE_ANTIALIAS_ON);

		// 填充位图背景
		g.setColor(_CodeBackgroundColor);
		g.fillRect(0, 0, width, height);

		g = (Graphics2D) g.create();
		// 水印
		Color watermarkColor = new Color(200, 200, 200);
		// Color watermarkColor = new Color(19,62,168) ;
		g.setColor(watermarkColor);
		Font watermarkFont = new Font("宋体", Font.CENTER_BASELINE, height - 9);
		g.setFont(watermarkFont);
		g.drawString("9istock.com", 3, 35);

		// 写文字内容
		Font textFont = null;
		Color textColor = new Color(19, 62, 168);
		g.setPaint(textColor);
		g.translate(width / 2, height / 2);
		for (int i = 0; i < count; i++) {
			int fontSize = 40 + random.nextInt(_CodeFontSizeRandScope);
			// textFont = new Font(
			// _CodeFontName[random.nextInt(_CodeFontName.length)],Font.BOLD
			// ,fontSize //BOLD
			// );

			textFont = new Font("宋体", Font.BOLD, fontSize); // BOLD
			g.setFont(textFont);
			int angle = random.nextInt(2 * _CodeMaxTurnAngle)
					- _CodeMaxTurnAngle; // 得到随机的旋转角度
			double angle_D = angle * Math.PI / 180;
			g.rotate(angle_D);
			int imgHeight = (int) (Math.tan(angle_D) * ((22 * (i) + 1) - width / 2));

			// System.out.println(imgHeight);

			g.drawString(sRand_Image[i], 24 * (i) - width / 2 + 2, 39 - height
					/ 2 - imgHeight);
			g.rotate(-angle_D);
		}
		// 随机输出噪点(矩形)
		g = (Graphics2D) g.create();
		// 随机产生10条干扰线，使图象中的认证码不易被其它程序探测到
		for (int i = 0; i < 8; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = x - random.nextInt(width);
			int yl = random.nextInt(height);
			g.setColor(textColor);
			g.drawLine(x - width / 2, y - height / 2, (x + xl) - width / 2,
					(y + yl) - height / 2);
		}

		g = (Graphics2D) g.create();
		// Color rectColor = new Color(19,62,168);
		// g.setColor(rectColor);
		for (int i = 0; i < 15; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			g.drawRect(x - width / 2, y - height / 2, 1, 1);
		}

		// 图象生效
		g.dispose();
		return image;
	}

	public static void main(String[] arge) {
		for (int i = 0; i < 20; i++) {
			try {
				RandImage image = new RandImage(6);
				File file = new File("E:/test/image/" + i + ".jpeg");
				FileOutputStream fos = new FileOutputStream(file);
				BufferedImage bi = image.creatImage();
				
				ImageIO.write(bi, "JPEG", fos);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}
}
